import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/services/AudioService.dart';

class LandscapeDirectTransController extends GetxController {



  ScrollController firstScrollController = ScrollController();
  ScrollController secondScrollController = ScrollController();
  Timer? _timer;

  String checkFinnalToText = '';
  String checkFinnalFromText = '';

  var screenWidth = 0.0.obs;
  var screenHeight = 0.0.obs;

  AudioService audioService = Get.find<AudioService>();

  @override
  void onInit() {
    super.onInit();
    WidgetsFlutterBinding.ensureInitialized();

    SchedulerBinding.instance.addPostFrameCallback((_) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeRight,
        DeviceOrientation.landscapeLeft,
      ]);
      _setFullScreen();
    });



    //每秒去检查一下字符串是否有变化,有变化则调用_autoScrollToBottom
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (checkFinnalToText != audioService.indexPageFinalToLanguage.value) {
        checkFinnalToText = audioService.indexPageFinalToLanguage.value;
        _autoScrollToBottomTo();
      }

      if (checkFinnalFromText != audioService.indexPageFinalFromLanguage.value) {
        checkFinnalFromText = audioService.indexPageFinalFromLanguage.value;
        _autoScrollToBottomFrom();
      }

    });
  }

  @override
  void onReady() {
    super.onReady();

    screenWidth.value = MediaQuery.of(Get.context!).size.width;
    screenHeight.value = MediaQuery.of(Get.context!).size.height;
    /*// 延迟到下一帧执行，确保布局完成
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _autoScrollToBottom();
    });*/
  }

  @override
  void onClose() {
    super.onClose();
    if (_timer != null) {
      _timer!.cancel();
    }


    // 页面退出时恢复系统UI（可选）
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }


  void _setFullScreen() {
    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.immersiveSticky,
      // 可选：隐藏特定系统栏（根据需求选择）
      overlays: [
        // SystemUiOverlay.top,    // 显示状态栏
        // SystemUiOverlay.bottom, // 显示导航栏
      ],
    );
  }

  void _autoScrollToBottomTo() {
    // 使用 animateTo 实现平滑滚动
    firstScrollController.animateTo(
      firstScrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }

  void _autoScrollToBottomFrom() {
    // 使用 animateTo 实现平滑滚动
    secondScrollController.animateTo(
      secondScrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }
}
